package com.pansoft.openplanet.activity.child;

import android.app.AlertDialog;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.utilcode.util.ToastUtils;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 观察者钱包
 *
 * @author YQS
 */
public class ChildObserveWalletFragment extends BaseFragment implements View.OnClickListener, AuthorizationSignFragment.CreateObserveListener {
    private static final String TAG = "ChildObserveWallet";

    private View rootView;
    private TextView textview1;
    private TextView textView2;
    private EditText etWalletAddress;
    private Button butNext;

    private AccountDao accountDao;
    //默认存放keysTORE的 文件夹
    private String basePath;
    private String avatar;
    private String walletAvatar;
    private String walletName;
    private String number;

    private String userName;
    private TCAccountManager tcAccountManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.talk_chain_fragment_child_observe_wallet, null);
        initView();
        initData();
        return rootView;
    }

    private void initView() {
        textview1 = (TextView) rootView.findViewById(R.id.textview1);
        textView2 = (TextView) rootView.findViewById(R.id.textView2);
        etWalletAddress = (EditText) rootView.findViewById(R.id.et_wallet_address);
        butNext = (Button) rootView.findViewById(R.id.but_next);
        butNext.setOnClickListener(this);
    }

    private void initData() {
        number = getActivity().getIntent().getExtras().getString("number");
        userName = getActivity().getIntent().getExtras().getString("userName");
        avatar = getActivity().getIntent().getStringExtra("avatar");
        walletAvatar = getActivity().getIntent().getStringExtra("wallet_avatar");
        walletName = getActivity().getIntent().getStringExtra("wallet_name");
        accountDao = new AccountDao(getActivity());
        tcAccountManager = new TCAccountManager(getActivity());

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.but_next) {
            goToNext();
        }
    }

    private void goToNext() {
        String address = etWalletAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.showShort(R.string.open_planet_wallet_address_not_null);
            return;
        }
        if (address.length() != 42) {
            ToastUtils.showShort(R.string.open_planet_wallet_address_incorrect);
            return;
        }
        Account account = accountDao.getAccount(address);
        if (account != null) {
            ToastUtils.showShort(R.string.open_planet_wallet_already_exist);
            return;
        }
        //显示dialog
        AuthorizationSignFragment authorizationSignFragment = AuthorizationSignFragment.newInstance(address);
        authorizationSignFragment.setCreateObserveListener(this);
        authorizationSignFragment.show(getFragmentManager(), TAG);

    }

    @Override
    public void startCreate(final String address, final String publicKey) {

        //生成的账户放到服务器
        tcAccountManager.addChildWallet1(publicKey, "", address, walletAvatar, walletName
                , IPAssetsConstant.ChainEnum.ETH.chainName, "2", null, "", new TCAccountManager.AccountManagerListener<String>() {
                    @Override
                    public void onSuccess(String object) {
                        TCLoadingDataView.dismiss();
                        //存入数据库
                        Account account = new Account();
                        account.setAccountAvatar(walletAvatar);
                        account.setAcccountName(walletName);
                        account.setEnable(true);
                        account.setAddress(address);
                        //16进制的publickey 转成10进制存储
                        account.setPublicKey(TCAccountManager.convertTo10Radix(publicKey));
                        account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                        account.setMaster(false);
                        account.setCurrentShow(false);
                        account.setAccountType(Account.ACCOUNT_TYPE_OBSERVE);//1观察者钱包
                        account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                        accountDao.insertOrReplace(account);
                        ToastUtils.showShort(R.string.open_planet_import_observe_wallet_success);
                        ActivityCompat.finishAffinity(getActivity());

                    }

                    @Override
                    public void onFail(String fail) {
                        TCLoadingDataView.dismiss();
                        showFailAlert(null);
                    }
                });


    }

    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_import_observe_wallet_fail_retry);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, null)
                .create()
                .show();
    }
}
